package com.qijian.common.utils.uuid;

import com.qijian.common.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 基于redis自增序列的单号
 */
@Component
public class RedisIdUtil {

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 返回按当前时间的 默认4位后缀的编号 例: BYJH-202401010001
     * @param keyPrefix 编号前缀
     * @return
     */
    public String getNumber(String keyPrefix){
        return getNumber(keyPrefix,4);
    }

    public  String getNumber(String keyPrefix,int length) {
        if(length<=0){
            throw new ServiceException("E01:序号后缀长度需大于0");
        }
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyMMdd");
        LocalDate date = LocalDate.now();
        String dateKey = date.format(fmt);
        String key = keyPrefix+":"+dateKey;
        Long increment = redisTemplate.opsForValue().increment(key);
        if (increment == null) {
            //重试一次
            increment = redisTemplate.opsForValue().increment(key);
        }
        //仍然为null,提示错误
        if(increment == null){
            throw new ServiceException("E01:生成序号失败,请重试");
        }
        if(Objects.equals(increment,1L)){
            redisTemplate.expire(key, 1, TimeUnit.DAYS);
        }
        String lengthFormat = "%0"+length+"d";
        return keyPrefix+"-"+dateKey + String.format(lengthFormat, increment);
    }
}
